import { login, logout } from '@/api/login'
import {
  setToken,
  removeToken,
  setUser,
  setPermissions
} from '../../common/auth'
import { SUCCESS_CODE } from '../../config/config'

const SET_USER = 'SET_USER'
const SET_TOKEN = 'SET_TOKEN'
const SET_PERMISSIONS = 'SET_PERMISSIONS'

const user = {
  state: {
    token: null,
    user: {},
    permissions: null
  },
  mutations: {
    [SET_USER](state, user) {
      state.user = user
    },
    [SET_TOKEN](state, token) {
      state.token = token
    },
    [SET_PERMISSIONS](state, permissions) {
      state.permissions = permissions
    }
  },
  getters: {
    token: state => state.token
  },
  actions: {
    // 用户登录
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(resp => {
            if (resp.data.status === SUCCESS_CODE) {
              let user = resp.data.data
              let token = user.token
              commit(SET_USER, user)
              setUser(user)
              commit(SET_TOKEN, token)
              setToken(token)
              setPermissions(user.permissions)
              commit(SET_PERMISSIONS, user.permissions)
            }
            return resolve({ status: resp.data.status, msg: resp.data.msg })
          })
          .catch(err => {
            return reject(err)
          })
      })
    },
    // 用户退出登录
    logout({ commit }) {
      return new Promise((resolve, reject) => {
        removeToken()
        commit(SET_TOKEN, '')
        resolve()
      })
    }
  }
}

export default user
